package com.atgugui.eduorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atgugui.commonutils.ResultCode;
import com.atgugui.eduorder.entity.TOrder;
import com.atgugui.eduorder.entity.TPayLog;
import com.atgugui.eduorder.mapper.TPayLogMapper;
import com.atgugui.eduorder.service.TOrderService;
import com.atgugui.eduorder.service.TPayLogService;
import com.atgugui.eduorder.utils.HttpClientUtils;
import com.atgugui.servicebase.exceptionhandler.GuLiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-09-15
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private TOrderService tOrderService;

    @Override
    public HashMap<String, Object> createPayQRCodeByOrderNo(String orderNo) {
        try {
            /**
             * 微信二维码流程
             */
            // 1.根据订单编号获取订单信息
            QueryWrapper<TOrder> tOrderQueryWrapper = new QueryWrapper<>();
            tOrderQueryWrapper.eq("order_no",orderNo);
            TOrder curOrder = tOrderService.getOne(tOrderQueryWrapper);

            // 2.设置支付参数，将支付参数放置到map中方便方便获取(详情参考微信官方文档)
            HashMap<String,Object> WxPayParamsMap = new HashMap<>();
            WxPayParamsMap.put("appid", "wx74862e0dfcf69954");
            WxPayParamsMap.put("mch_id", "1558950191");
            WxPayParamsMap.put("nonce_str", WXPayUtil.generateNonceStr());
            WxPayParamsMap.put("body", curOrder.getCourseTitle()); // 当前订单的
            WxPayParamsMap.put("out_trade_no", orderNo);
            WxPayParamsMap.put("total_fee", curOrder.getTotalFee().multiply(new BigDecimal("10")).longValue()+"");
            WxPayParamsMap.put("spbill_create_ip", "127.0.0.1");
            WxPayParamsMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            WxPayParamsMap.put("trade_type", "NATIVE");

            //3.HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数(参数类型必须是顶层父类Map类型，不能是子类类型，否则报错)
            client.setXmlParam(WXPayUtil.generateSignedXml((Map)WxPayParamsMap, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            String xml = client.getContent(); // 将上述的参数返回一个xml格式类型的文件
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml); // 将xml文件类型转化为map类型

            // 4.
            HashMap<String,Object> qrMap = new HashMap<>();
            qrMap.put("out_trade_no", orderNo);
            qrMap.put("course_id", curOrder.getCourseId());
            qrMap.put("total_fee", curOrder.getTotalFee());
            qrMap.put("result_code", resultMap.get("result_code")); // 二维码操作的状态码
            qrMap.put("code_url", resultMap.get("code_url")); // 二维码地址
            return qrMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuLiException(ResultCode.ERROR,"支付二维码生成失败");
        }
    }

    @Override
    public HashMap<String, String> getPayStatusMap(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2 发送httpclient  都是通过http请求第三方接口实现
            HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            //3 得到请求返回内容
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map再返回
            return (HashMap<String, String>) resultMap;
        }catch(Exception e) {
            return null;
        }
    }

    @Override
    public void updateOrdersStatus(HashMap<String, String> statusMap) {
        //从map获取订单号
        String orderNo = statusMap.get("out_trade_no");
        //根据订单号查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = tOrderService.getOne(wrapper);

        //更新订单表订单状态
        if(order.getStatus().intValue() == 1) { return; }
        order.setStatus(1);//1代表已经支付
        tOrderService.updateById(order);

        //向支付表添加支付记录
        TPayLog payLog = new TPayLog();
        payLog.setOrderNo(orderNo);  //订单号
        payLog.setPayTime(new Date()); //订单完成时间
        payLog.setPayType(1);//支付类型 1微信
        payLog.setTotalFee(order.getTotalFee());//总金额(分)

        payLog.setTradeState(statusMap.get("trade_state"));//支付状态
        payLog.setTransactionId(statusMap.get("transaction_id")); //流水号
        payLog.setAttr(JSONObject.toJSONString(statusMap));

        baseMapper.insert(payLog);
    }
}
